<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service;

use app\command\DailyStatWork;
use app\model\CrontabTaskBadLogModel;
use app\model\CrontabTaskModel;

class CrontabTaskService extends BaseService
{
    /**
     * 设置任务.
     */
    public static function setSingleTask(DailyStatWork $model): bool
    {
        $obj = $model->getCrontabTaskInfo();

        if ($obj instanceof CrontabTaskModel) {
            if ($obj->getKey() > 0) {
                $obj->last_finish_time = $obj->finish_time;
                $obj->finish_time = time();
            } else {
                $obj = new CrontabTaskModel();
                $obj->task_name = $model->getCommandName();
                $obj->tag = $model->getTag();
                $obj->path = '\\app\\command\\' . $model->getCommandName();
                $obj->finish_time = time();
                $obj->status = CrontabTaskModel::STATUS_ENABLE;
            }

            return $obj->save();
        }
        return true;
    }

    /**
     * 失败key插回队尾.
     * @param mixed $msg
     */
    public static function fallPushList(object $redis, string $redisKey, string $advertiser_id, int $execNum, $msg = '')
    {

        if ($execNum < 10) {
            if (strpos($msg, 'Application has reached the request limit per minute') === false) {
                $execNum = $execNum + 1;
            }
            $key = $advertiser_id . '_' . $execNum . '_' . time();
            return $redis->rPush($redisKey, $key);
        }
        // 如果次数多于规定次数，存记录表
        $data = [
            'advertiser_id' => $advertiser_id,
            'redis_key' => $redisKey,
            'exec_num' => $execNum,
            'stat_date' => date('Y-m-d H:i:s'),
            'msg' => $msg,
        ];
        return CrontabTaskBadLogModel::create($data);
    }
}
